<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Admin\AuthGroup as AuthGroupModel;
use App\Models\Admin\AuthGroupAccess as AuthGroupAccessModel;
use App\Models\Config as ConfigModel;

class Admin extends Model
{
    use HasFactory;

    protected $table = 'admin';

    // 自动写入时间戳
    public $timestamps = true;

    // 时间类型
    protected $dateFormat = 'U';

    // 自定义创建时间字段
    const CREATED_AT = 'createtime';

    // 自定义更新时间字段
    const UPDATED_AT = 'updatetime';

    protected $appends = [
        'group_text',// 分组名称
        'avatar_cdn'
    ];

    public function getGroupTextAttribute()
    {
        // 获取分组id
        $gid = AuthGroupAccess::where(['uid' => $this->id])->value('group_id');
    
        if(empty($gid))
        {
            return '暂无角色组';
        }

        $name = AuthGroupModel::where(['id' => $gid])->value('name');

        if(empty($name))
        {
            return '暂无角色组名称';
        }

        return $name;
    
    }

    public function getAvatarCdnAttribute()
    {
        $cdn = ConfigModel::where(['name' => 'url'])->value('value');

        $url = $cdn . '/stock/admin/avatar';

        $avatar = httpRequest($url,['id' => $this->id]);

        return $avatar;
    }
}
